package com.darkfire.weixinJDBC;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class Tools {
    private  final  static Tools instance=new Tools(); //创建饿汉单例模式

    Tools(){

    }

    public static Tools getInstance(){
        return instance;
    }

    public  String sendGet(String url_){
        URL url;
        int responsecode;
        HttpURLConnection urlConnection;
        BufferedReader reader;
        String line;
        String html="";
        try{
            url=new URL(url_);
            urlConnection = (HttpURLConnection)url.openConnection();
            responsecode=urlConnection.getResponseCode();
            if(responsecode==200){
                reader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"GBK"));
                while((line=reader.readLine())!=null){
                    html=html+line;
                }
                return html;
            }
            else{
                System.out.println("获取不到网页的源码，服务器响应代码为："+responsecode);
            }
        }
        catch(Exception e){
            System.out.println("获取不到网页的源码,出现异常："+e);
        }
        return "get error";
    }


    public String sendPost(String url,String json) {
        JSONObject jsonParam = null;
        try{
            jsonParam = new JSONObject(json);
        }catch (Exception e){
            e.printStackTrace();
            return "json error";
        }

        //创建post请求对象 发送json数据
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json;charset=utf-8");
        try {
            HttpClient client = new DefaultHttpClient();
            StringEntity se = new StringEntity(jsonParam.toString(), "utf-8");
            post.setEntity(se); // post方法中，加入json数据
            HttpResponse response = client.execute(post);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String result = EntityUtils.toString(resEntity, "utf-8");
                    return  result;
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
            return "post error";
        }
        return "post error";
    }

}

